using System;
using System.Text;
using System.Security.Cryptography;
using System.Configuration;
using System.IO;
using System.Xml;
using System.Collections.Generic;

namespace ProjectBase.Utils
{
	/// <summary>
	/// Summary description for CSecurity.
	/// </summary>
	public class CSecurity
	{
		public CSecurity()
		{
			//
			// TODO: Add constructor logic here
			//
		}
		static TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
		static string privateKey = "XUenPktGV8KqWFr6RfE2r0Uljn/yV2i0";
		static string privateIV = "tpdgrWJQj0Q=";
		public static string EncodeSTR_MD5(string thisEncode)
		{
			string encrypted;
			byte[] Code = ASCIIEncoding.ASCII.GetBytes(thisEncode);
		
			MD5 des = new MD5CryptoServiceProvider();
			encrypted = Convert.ToBase64String(des.ComputeHash(Code, 0, Code.Length));
			return encrypted;
		}
	
		private static string Encode(string thisEncode)
		{
			string encrypted;
			byte[] Code = ASCIIEncoding.ASCII.GetBytes(thisEncode);
		
			encrypted = Convert.ToBase64String(
				des.CreateEncryptor().TransformFinalBlock(Code, 0, Code.Length)
				);
		
			return encrypted;
		}
		private static string Decode(string thisDecode)
		{
			string decrypted;
			byte[] Code = Convert.FromBase64String(thisDecode);
		
			decrypted = ASCIIEncoding.ASCII.GetString(
				des.CreateDecryptor().TransformFinalBlock(Code, 0, Code.Length)
				);

			return decrypted;
		}
		
		public static string EncodeSTR(string thisEncode)
		{
			TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
			des.IV = Convert.FromBase64String(privateIV);
			des.Key = Convert.FromBase64String(privateKey);
			string encrypted;
			byte[] Code = ASCIIEncoding.ASCII.GetBytes(thisEncode);
		
			encrypted = Convert.ToBase64String(
				des.CreateEncryptor().TransformFinalBlock(Code, 0, Code.Length)
				);
		
			return encrypted;
		}
	
		public static string EncodeSTR(string thisEncode, string strKey)
		{
			TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
			des.IV = Convert.FromBase64String(privateIV);
			if(strKey!=null&&strKey!="")
			{
				des.Key = Convert.FromBase64String(strKey);
			}
			else
			{
				des.Key = Convert.FromBase64String(privateKey);
			}
			string encrypted;
			byte[] Code = ASCIIEncoding.ASCII.GetBytes(thisEncode);
		
			encrypted = Convert.ToBase64String(
				des.CreateEncryptor().TransformFinalBlock(Code, 0, Code.Length)
				);
		
			return encrypted;
		}
	
		public static string DecodeSTR(string thisDecode)
		{
			TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
			des.IV = Convert.FromBase64String(privateIV);
			des.Key = Convert.FromBase64String(privateKey);
			string decrypted;
			byte[] Code = Convert.FromBase64String(thisDecode);
		
			decrypted = ASCIIEncoding.ASCII.GetString(
				des.CreateDecryptor().TransformFinalBlock(Code, 0, Code.Length)
				);

			return decrypted;
		}
		public static string DecodeSTR(string thisDecode, string strKey)
		{
			TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
			des.IV = Convert.FromBase64String(privateIV);
			if(strKey!=null&&strKey!="")
			{
				des.Key = Convert.FromBase64String(strKey);
			}
			else
			{
				des.Key = Convert.FromBase64String(privateKey);
			}
			string decrypted;
			byte[] Code = Convert.FromBase64String(thisDecode);
		
			decrypted = ASCIIEncoding.ASCII.GetString(
				des.CreateDecryptor().TransformFinalBlock(Code, 0, Code.Length)
				);

			return decrypted;
		}
		/// <summary>
		/// Returns the path and filename of the configuration file.
		/// </summary>
		private static string getConfigPath() 
		{
			string cfgPath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
			cfgPath = cfgPath.Replace("/", "\\");
			cfgPath = Path.GetDirectoryName(cfgPath);
			
			return Path.Combine(cfgPath, "settings.xml");
		}

		/// <summary>
		/// Gets a setting from XML
		/// </summary>
		public static string getSetting(string key) 
		{
			// Create a new XML Document and load the cfg file
			XmlDocument xmlDoc = new XmlDocument();

			// Set our key
			des.Key = Convert.FromBase64String(privateKey);
			
			// Load the file
			if (File.Exists(getConfigPath())) xmlDoc.Load(getConfigPath());

			// Look for our key
			XmlNode keyNode = xmlDoc.SelectSingleNode("//appSettings/add[@key='" + key + "']");

			// Found it
			if ( keyNode != null ) 
			{
				// Get the value
				string Value = keyNode.Attributes["value"].Value;

				// Is it encoded ?
				if (keyNode.Attributes["encode"] != null)
				{
					// Set the public key to the value of encoded
					des.IV = Convert.FromBase64String(keyNode.Attributes["encode"].Value);
					
					// Decrypt the value
					Value = Decode(keyNode.Attributes["value"].Value);
				}

				return Value;
			}
			else
			{
				return "";
			}
		}

		/// <summary>
		/// Write Setting
		/// </summary>
		public static void writeSetting(string key, string keyValue, bool encode) 
		{
			// Create a new XML Document and load the cfg file
			XmlDocument xmlDoc = new XmlDocument();

			// Set our key
			des.Key = Convert.FromBase64String(privateKey);

			// Load the file
			if (File.Exists(getConfigPath())) xmlDoc.Load(getConfigPath());

			// Look for appSettings
			XmlNode appSettings = xmlDoc.SelectSingleNode("//appSettings");

			// No appSettings so create it
			if ( appSettings == null ) 
			{
				appSettings = xmlDoc.CreateElement("appSettings");
				xmlDoc.AppendChild(appSettings);
			}

			// Look for our key
			XmlNode keyNode = xmlDoc.SelectSingleNode("//appSettings/add[@key='" + key + "']");

			// Found it
			if ( keyNode != null ) 
			{
				// We found it so just update the value
				XmlNode myAttribute = keyNode.Attributes["value"];
				
				// Was it encoded ?
				if (keyNode.Attributes["encode"] != null) 
				{
					// Generate new public key (Cant be to safe)
					des.GenerateIV();
					
					// Set the values
					keyNode.Attributes["encode"].Value = Convert.ToBase64String(des.IV);
					keyNode.Attributes["value"].Value = Encode(keyValue);
				}
				else
				{
					keyNode.Attributes["value"].Value = keyValue;
				}
			}
			else
			{
				// We didnt find it, so create it.
				keyNode = xmlDoc.CreateElement("add");

				// Set the POSSIBLE attributes
				XmlAttribute newKey = xmlDoc.CreateAttribute("key");
				XmlAttribute newValue = xmlDoc.CreateAttribute("value");
				XmlAttribute newEncode = xmlDoc.CreateAttribute("encode");
				
				// Set the keyName
				newKey.Value = key;

				if (encode)
				{
					// Generate new public key
					des.GenerateIV();
					des.Key = Convert.FromBase64String(privateKey);

					// Set the values
					newEncode.Value = Convert.ToBase64String(des.IV);
					newValue.Value = Encode(keyValue);

					// Append the attributes
					keyNode.Attributes.Append(newKey);
					keyNode.Attributes.Append(newEncode);
					keyNode.Attributes.Append(newValue);
				}
				else
				{
					// Not encoded, ok set it.
					newValue.Value = keyValue;

					// Append the attributes
					keyNode.Attributes.Append(newKey);
					keyNode.Attributes.Append(newValue);
				}

				// Add the key
				appSettings.AppendChild(keyNode);
			}

			xmlDoc.Save(getConfigPath());
		}

	}
}
